package com.example.client_group5;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import org.json.JSONObject;

import util.HttpClientFactory;


import android.os.Bundle;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class SignInActivity extends Activity {

	private EditText editTextUser;
	private EditText editTextPass;
	private View signInButton;
	private View signUpButton;
	public static UserManager userProfile;
	 // Progress dialog static
	 public static ProgressDialog dialog;
	// static client 
	public static DefaultHttpClient client;
	// static share preferences
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.sign_in);
        userProfile = new UserManager(this, "USER");
        if(client == null){
        	client = HttpClientFactory.getThreadSafeClient();
        }
      
    	Log.d("flag", "pivot: " + userProfile.getUserName("username", ""));
    	if(userProfile.getUserName("username",  "").equals("")){
	        editTextUser = (EditText)findViewById(R.id.username);
	        editTextPass = (EditText)findViewById(R.id.password);
	        signInButton = (View)findViewById(R.id.btSignin);
	        signInButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//Log.d("tag", "User: " + editTextUser.getText().toString());
					//Log.d("tag", "Pass: " + editTextPass.getText().toString());
					String username = editTextUser.getText().toString();
					String password = editTextPass.getText().toString();
					postData(username, password);
				}
			});
	        editTextUser.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub
					
					if(!editTextUser.getText().toString().equals("") && !editTextPass.getText().toString().equals("")){
						if(!signInButton.isEnabled()){
							signInButton.setEnabled(true);
							signInButton.setBackgroundResource(R.drawable.bg_signin_yellow);
						}
					}
					else{
						if(signInButton.isEnabled()){
							signInButton.setEnabled(false);
							signInButton.setBackgroundResource(R.drawable.bg_button_sign);
						}
					}
					
				}
	
				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub
					
				}
	
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
					// TODO Auto-generated method stub
					
				}
			});
	        editTextPass.addTextChangedListener(new TextWatcher() {
				
				@Override
				public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
					// TODO Auto-generated method stub
					if(!editTextUser.getText().toString().equals("") && !editTextPass.getText().toString().equals("")){
						if(!signInButton.isEnabled()){
							signInButton.setEnabled(true);
							signInButton.setBackgroundResource(R.drawable.bg_signin_yellow);
						}
					}
					else{
						if(signInButton.isEnabled()){
							signInButton.setEnabled(false);
							signInButton.setBackgroundResource(R.drawable.bg_button_sign);
						}
					}
				}
				
				@Override
				public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
						int arg3) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub
					
				}
			});
	        signUpButton = (View)findViewById(R.id.btSignup);
	        signUpButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent i = new Intent(SignInActivity.this, SignUpActivity.class);
					startActivity(i);
					finish();
				}
			});
    	}
    	else{
    		String username = userProfile.getUserName("username", "");
    		String password = userProfile.getPassword("password", "");
    		Log.d("username", "username: " + username);
    		Log.d("password", "password: " + password);
    		postData(username, password);
    	}
    }
    public void postData(String username, String password){
    	try{
    		//dialog = ProgressDialog.show(this, "Please waiting", "Loading", false, true);
    		
    		ResponseHandler <String> res=new BasicResponseHandler();  
    	
    		String postUrl = Setting.ipServer + "api/auth/login";
    		
    		HttpPost postMethod = new HttpPost(postUrl);  
    		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);    
    		Log.d("tag", "username / password: " + username + "		" + password);
    		nameValuePairs.add(new BasicNameValuePair("username", username.trim()));    
    		nameValuePairs.add(new BasicNameValuePair("password", password.trim()));    
    		postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
    		
    		//String response = hc.execute(postMethod,res); 
    		String response = client.execute(postMethod,res); 
    		
    		Log.d("AAA", "TRA VE: " + response);
    		
    		JSONObject jsonObject = null;
    		jsonObject = new JSONObject(response);
    		Object result = jsonObject.get("isLogin");
			Log.d("tag", "Result: " + result.toString());
			if(result.toString().equals("true")){
				if(userProfile.getUserName("username", "").equals("")){
					JSONObject userInfo = jsonObject.getJSONObject("userinfo");
					String user_id = userInfo.getString("user_id");
					String fullname = userInfo.getString("fullname");
					String bio = userInfo.getString("bio");
					String avatarLink = userInfo.getString("avatar");
					String localtion = userInfo.getString("location");
					String web = userInfo.getString("web");
					
					userProfile.saveAvatar("avatar", avatarLink);
					userProfile.saveFullName("fullname", fullname);
					userProfile.saveUserName("username", username);
					userProfile.savePassword("password", password);
					userProfile.saveUserId("userId", user_id);
					userProfile.saveLocation("location", localtion);
					userProfile.saveBio("bio", bio);
					userProfile.saveWeb("web", web);
				}
				Intent i = new Intent(SignInActivity.this, MainActivity.class);
				startActivity(i);
				finish();
			}
			else{
//				dialog.dismiss();
				Toast toast = Toast.makeText(SignInActivity.this, "Invalid username or password", Toast.LENGTH_LONG);
				toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 100);
				toast.show();
			}
    		
    		
    	}catch(Exception e){
    		e.printStackTrace();
    	}
 
    }
    
   
}
